package com.voxel.sense.infomsg.net;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.voxel.sense.infomsg.BuildConfig;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.CommonConstants;
import cyy.example.com.facotry.share.SPEngine;
import me.jessyan.progressmanager.ProgressManager;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class UpDownNetwork {
    private static UpDownNetwork instance;
    private Retrofit retrofit;

    static {
        instance = new UpDownNetwork();
    }

    private UpDownNetwork() {

    }

    // 构建一个Retrofit
    public static Retrofit getRetrofit() {
        if (instance.retrofit != null)
            return instance.retrofit;

        OkHttpClient client = createHttpClient();
        Retrofit.Builder builder = new Retrofit.Builder();

        // 设置电脑链接
        instance.retrofit = builder.baseUrl(CommonConstants.API_URL_PREFIX)
                // 设置client
                .client(client)
                // 设置Json解析器
                .addConverterFactory(GsonConverterFactory.create(Factory.getGson()))
                .build();

        return instance.retrofit;
    }

    @NonNull
    private static OkHttpClient createHttpClient() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        if (BuildConfig.DEBUG) {
            logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        } else {
            logging.setLevel(HttpLoggingInterceptor.Level.NONE);
        }

        // 得到一个OK Client 
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
//                 给所有的请求添加一个拦截器
                .addInterceptor(logging)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Request.Builder builder = request.newBuilder();
                        SPEngine spEngine = SPEngine.getSPEngine();
                        if (!TextUtils.isEmpty(spEngine.getUserInfo().getSetMobileToken())) {
                            // 添加公用的头
                            builder.addHeader("Authorization", SPEngine.getSPEngine().getUserInfo().getSetMobileToken());
                        }
                        builder.addHeader("device", "mobile");
                        boolean loginState = SPEngine.getSPEngine().isLoginState();
                        if (loginState){
                            String user_id = spEngine.getUserInfo().getUser_id();
                            builder.addHeader("_userId",user_id);
                        }
                        //创建新的request
                        Request newRequest = builder.build();
                        Response response = chain.proceed(newRequest);
                        return response;
                    }
                })
                //设置超时
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS);

        //将builder注入到下载监听及上传监听的管理器中
        OkHttpClient.Builder with = ProgressManager.getInstance().with(builder);
        return with.build();
    }

    /**
     * 返回一个请求代理
     *
     * @return RemoteService
     */
    public static FileOperatorRemoteService remote() {
        return UpDownNetwork.getRetrofit().create(FileOperatorRemoteService.class);
    }

}
